class Client < ActiveRecord::Base
  include Perishable
  include SecretAccessible

  belongs_to :room
  validates_presence_of   :name , :nicks , :secret , :type , :room_id
  validates_presence_of   :name , :nicks , :secret , :type , :room_id
  validates_uniqueness_of :name , :secret
  before_validation :prepare , :on => :create
  after_create      :prefill_messages
  before_destroy    :destroy_room


private

  def prepare
    self.name    &&= URI.escape self.name
    self.secret    = generate_secret
    self.room      = Room.create

    raise ActiveRecord::RecordNotUnique , "" if (Client.find_by_name   self.name  ).present? ||
                                                (Client.find_by_secret self.secret).present?
  end

  def prefill_messages
    N_MESSAGES_QUEUED.times { self.room.messages.create PRIME_MESSAGE_PARAMS }
  end

  def destroy_room ; self.room.destroy if self.room.clients.count == 1 ; end ;

  def self.all_stale
    Perishable.all_stale.map { | id | self.find id }
  end

  def self.cleanup # NOTE: cron this
    Client.all_stale.each { | client | p "destroying client ##{client.id}" ; client.destroy ; }
    Room  .all_empty.each { | room   | p "destroying room ##{  room  .id}" ; room  .destroy ; }
  end
end


class IrcClient < Client ; end ;
class SimClient < Client ; end ;
